/**
 * @description 数据备份工具类
 * @author AI Assistant
 * @date 2023-10-27
 */

import { storage, STORAGE_KEYS } from './storage'

export const backup = {
  // 创建备份
  create() {
    try {
      const data = {}
      Object.values(STORAGE_KEYS).forEach(key => {
        data[key] = storage.get(key)
      })
      return JSON.stringify(data)
    } catch (e) {
      console.error('Backup create error:', e)
      return null
    }
  },

  // 恢复备份
  restore(backupData) {
    try {
      const data = JSON.parse(backupData)
      Object.entries(data).forEach(([key, value]) => {
        storage.set(key, value)
      })
      return true
    } catch (e) {
      console.error('Backup restore error:', e)
      return false
    }
  },

  // 导出备份到文件
  exportToFile() {
    try {
      const backupData = this.create()
      if (!backupData) return false

      const fileName = `ticktock_backup_${new Date().toISOString().replace(/[:.]/g, '-')}.json`
      
      // 在不同平台上使用不同的导出方法
      // #ifdef H5
      const blob = new Blob([backupData], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = fileName
      link.click()
      URL.revokeObjectURL(url)
      return true
      // #endif
      
      // #ifdef APP-PLUS
      const fs = uni.getFileSystemManager()
      const path = `${uni.env.USER_DATA_PATH}/${fileName}`
      fs.writeFileSync(path, backupData, 'utf8')
      uni.shareFileMessage({
        filePath: path,
        success: () => console.log('Backup shared successfully'),
        fail: (err) => console.error('Backup share failed', err)
      })
      return true
      // #endif
      
      // #ifdef MP
      uni.setClipboardData({
        data: backupData,
        success: () => {
          uni.showToast({
            title: '备份数据已复制到剪贴板',
            icon: 'none'
          })
        }
      })
      return true
      // #endif
      
      return false
    } catch (e) {
      console.error('Backup export error:', e)
      return false
    }
  },

  // 从文件导入备份
  importFromFile(filePath) {
    try {
      // #ifdef APP-PLUS
      const fs = uni.getFileSystemManager()
      const backupData = fs.readFileSync(filePath, 'utf8')
      return this.restore(backupData)
      // #endif
      
      return false
    } catch (e) {
      console.error('Backup import error:', e)
      return false
    }
  },
  
  // 从剪贴板导入备份
  importFromClipboard() {
    try {
      return new Promise((resolve) => {
        uni.getClipboardData({
          success: (res) => {
            try {
              const result = this.restore(res.data)
              resolve(result)
            } catch (e) {
              console.error('Clipboard data is not valid backup', e)
              resolve(false)
            }
          },
          fail: () => {
            resolve(false)
          }
        })
      })
    } catch (e) {
      console.error('Backup clipboard import error:', e)
      return Promise.resolve(false)
    }
  }
} 